package cn.wanho.listener;


import cn.wanho.dto.CmsSummary;
import cn.wanho.service.CmsSummaryService;
import cn.wanho.rvo.myeasyexcel.CmsSummaryData;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author karry
 * @create 2022/6/9 15:44
 * @description: easyExcel监听
 */
@Component
@Scope("prototype")
@Slf4j
public class DataListenerA extends AnalysisEventListener<CmsSummaryData> {


     CmsSummaryService cmsSummaryService;
     Integer paperId;

    private static final int BATCH_COUNT = 10;
    //缓存数据
    private List<CmsSummaryData> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private CmsSummary summary;

    public DataListenerA() {
        summary = new CmsSummary();
    }

    public DataListenerA(CmsSummaryService qbService,Integer paperId) {
        this.cmsSummaryService = qbService;
        this.paperId=paperId;
    }

    @Override
    public void invoke(CmsSummaryData cmsSummaryData, AnalysisContext analysisContext) {
        // 每解析一行数据,该方法会被调用一次
        //System.out.println("解析到一条数据:"+ JSON.toJSONString(questionbankData));
        cachedDataList.add(cmsSummaryData);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //存入到数据库中
        saveData();
        // 全部解析完成被调用
        System.out.println("所有数据解析完成！！");
    }

    //存储到数据库
    private void saveData() {
        log.info(": 共计{}条数据，开始存储数据库！", cachedDataList.size());
        cmsSummaryService.insert(cachedDataList,paperId);
        System.out.println("数据插入数据库成功！！");
    }
}

